package com.changli05.communication.exer;


class Clerk {
    public int productNum;
    //生产者 生产产品
    public synchronized void addProduct(){
        if (productNum>=20){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }

        productNum++;
        System.out.println(Thread.currentThread().getName()+"生产了第"+productNum+"产品");
        notify();
    }
    //消费者消费产品
    public synchronized void minusProduct () {

        if(productNum <= 0){
            try {
                wait();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println(Thread.currentThread().getName()+"消费了第"+productNum+"产品");
        productNum--;
        notify();

    }

}



//生产者

class Producer implements Runnable{
    private Clerk clerk;
    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public synchronized void run() {
        while (true){
            System.out.println("生产者开始生产产品.....");
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            clerk.addProduct();
        }
    }
}


//消费者



class Consumer implements Runnable{
    private Clerk clerk;
    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public synchronized void run() {
        while (true){
            System.out.println("消费者开始消费产品.....");

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            clerk.minusProduct();
        }
    }
}





//主程序

public class ProducerConsumerTest {
    public static void main(String[] args) {
        Clerk  clerk = new Clerk();
        Thread pro1 = new Thread(new Producer(clerk));
        Thread con1 = new Thread(new Consumer(clerk));
        pro1.setName("生产者1");
        con1.setName("消费者1");
        pro1.start();
        con1.start();
    }

}
